﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.WebParts.IOAllProductsDropDown
{
    [ToolboxItem(false)]
    public class IOAllProductsDropDown : WebPart
    {
        private DropDownList _productsDropDown;

        /// <summary>
        /// Creates dropdown control.
        /// </summary>
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            Controls.Add(new LiteralControl("<fieldset>"));

            _productsDropDown = new DropDownList
            {
                ID = "_productsDropDown",
                DataTextField = "Title",
                DataValueField = "Id",
                AutoPostBack = true
            };
            _productsDropDown.SelectedIndexChanged += ProductsDropDownSelectedIndexChanged;
            Controls.Add(_productsDropDown);

            Controls.Add(new LiteralControl("</fieldset>"));
        }

        void ProductsDropDownSelectedIndexChanged(object sender, EventArgs e)
        {
            var pId = _productsDropDown.SelectedValue;
            var urlParams = new List<string>();

            if (!string.IsNullOrEmpty(pId))
            {
                urlParams.Add("p=" + pId);
            }

            Response.Redirect("Default.aspx?" + string.Join("&", urlParams.ToArray()));
        }

        /// <summary>
        /// Binds dropdown control to data.
        /// </summary>
        /// <param name="e">Event arguments.</param>
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            EnsureChildControls();

            var repository = new CompanyRepository(EnetaApplication.PortalCompaniesSiteUrl);
            IList<IoProduct> prods;

            try
            {
                prods = repository.GetAllProductsResults();
            }
            catch (Exception ex)
            {
                Logger.LogWarning("OnPreRender(): Exception when getting products");
                Logger.LogException(ex);
                return;
            }

            if (_productsDropDown == null)
            {
                Logger.LogWarning("OnPreRender(): Products dropdown is null");
                return;
            }

            try
            {
                _productsDropDown.DataSource = prods;
                _productsDropDown.DataBind();
            }
            catch (Exception ex)
            {
                Logger.LogWarning("OnPreRender(): Exception when binding companies");
                Logger.LogException(ex);
                return;
            }
            var item = new ListItem(Resources.GetResourceString("SelectProductDropDownLabel"), string.Empty);
            _productsDropDown.Items.Insert(0, item);

            var productId = Request.QueryString["p"] ?? string.Empty;
            if (_productsDropDown.Items.FindByValue(productId) != null)
                _productsDropDown.SelectedValue = productId;
        }

        /// <summary>
        /// Avoids additional begin tag of web part.
        /// </summary>
        /// <param name="writer"></param>
        public override void RenderBeginTag(HtmlTextWriter writer)
        {
        }

        /// <summary>
        /// Avoids additional end tag of web part.
        /// </summary>
        /// <param name="writer"></param>
        public override void RenderEndTag(HtmlTextWriter writer)
        {
        }

        private HttpRequest Request
        {
            get
            {
                return HttpContext.Current.Request;
            }
        }

        private HttpResponse Response
        {
            get
            {
                return HttpContext.Current.Response;
            }
        }
    }
}
